package com.mesSystem.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mesSystem.dto.Result;
import com.mesSystem.entity.PadManagement;
import com.mesSystem.entity.Workstation;
import com.mesSystem.service.impl.PadManagementService;
import com.mesSystem.service.impl.WorkstationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.web.bind.annotation.*;

import java.sql.Date;
import java.util.List;

@RestController
@Slf4j
@RequestMapping("padmanagement")
@ResponseBody
public class PadManagementController {
    @Autowired
    PadManagementService padManagementService;
    @Autowired
    WorkstationService workstationService;

    @PostMapping("increase")
    public Result increase(@RequestBody PadManagement padManagement) {
        try {
            // 判断工位是否存在
            if (workstationService.isNameNotExist(padManagement.getWorkstationName())) {
                // 如果没匹配的工位记录，则返回错误信息
                return Result.fail("工位名称不存在！");
            }
            padManagementService.save(padManagement);
        } catch (DataIntegrityViolationException e) {
            return Result.fail("pad名字或mac地址发生冲突！");
        }
        log.info("添加工位:{}",padManagement);
        return Result.ok("创建成功");
    }

    @DeleteMapping("delete")
    public Result delete(Long padManagementId) {
        padManagementService.removeById(padManagementId);
        return Result.ok("删除成功");
    }

    /**
     * 分页查询信息
     */
    @GetMapping("query")
    public Result query(@RequestParam(value = "page", defaultValue = "1") Integer page,
                        @RequestParam(value = "size", defaultValue = "10") Integer size) {
        // 创建分页器对象
        Page<PadManagement> Page = new Page<>(page, size);

        // 调用分页查询方法，将分页器传递给service
        padManagementService.page(Page, new QueryWrapper<PadManagement>().orderByAsc("pad_management_id"));

        // 从分页器对象中获取分页后的数据
        List<PadManagement> padManagements = Page.getRecords();

        log.info("被查询信息为：{}", padManagements);

        // 返回分页结果
        return Result.ok(padManagements);
    }

    /**
     * 更改
     */
    @PostMapping("update")
    public Result update(@RequestBody PadManagement padManagement) {
        if (padManagement.getPadManagementId() == null) {
            return Result.fail("没有传达工位id！");
        }
        padManagementService.updateById(padManagement);
        log.info("update:{}",padManagement);
        return Result.ok("更新成功");
    }
}
